from django.core.cache import cache
from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse
from django.views import View
from apps.areas.models import Area
import logging


class AreasView(View):

   def get(self,request):
        province_list = cache.get('province')
        if province_list is None:
            provinces = Area.objects.filter(parent=None)
            province_list = []
            for province in provinces:
                province_list.append({
                    'id': province.id,
                    'name': province.name
                })
            cache.set('province', province_list, 24*3600)

        return JsonResponse({'code': 0, 'errmsg': 'OK', 'province_list': province_list})


class SubAreaView(View):

    def get(self,request, id):
        cities_list = cache.get('city%s'%id)
        if cities_list is None:
            province = Area.objects.get(id=id)
            cities = province.subs.all()
            data_list = []
            for city in cities:
                data_list.append({
                    'id':city.id,
                    'name': city.name
                })
            cache.set('city:%s'%id,data_list,24*3600)
        return JsonResponse({'code': 0, 'errmsg':'OK', 'sub_data': {'subs': data_list}})
